#!/usr/bin/env python
#
# A plugin for requesting perfmon actions via the xe host-call-plugin mechanism

import XenAPIPlugin
import os
import socket

# TODO: put this info plus all the supported cmds in a shared file
cmdsockname = "\0perfmon"  # an af_unix socket name (the "\0" stops socket.bind() creating a fs node)
cmdmaxlen = 256

def send_perfmon_cmd(cmd):
    "Return True for success, or ERROR_%d: <msg> otherwise"
    if len(cmd) >= cmdmaxlen:
        return "ERROR_0: command too long"
    try:
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
        rc = sock.sendto(cmd, cmdsockname)
    except socket.error as e:
        err, msg = e.args
        return "ERROR_%d: %s" % (err, msg)
    except Exception:
        return "ERROR_1: unknown error"

    return str(rc == len(cmd))


def stop(session, args):
    rc = os.system("/etc/init.d/perfmon stop &>/dev/null")
    return str(rc == 0)

def start(session, args):
    rc = os.system("/etc/init.d/perfmon start &>/dev/null")
    return str(rc == 0)

def restart(session, args):
    rc = os.system("/etc/init.d/perfmon restart &>/dev/null")
    return str(rc == 0)
    
def refresh(session, args):
    return send_perfmon_cmd("refresh")

def debug_mem(session,args):
    return send_perfmon_cmd("debug_mem")

if __name__ == "__main__":
    XenAPIPlugin.dispatch({"stop": stop, "start": start, "restart": restart, "refresh": refresh, "debug_mem": debug_mem})

